package com.njit.mailm.core.service.impl;

import com.njit.mailm.commmon.utils.IOUtil;
import com.njit.mailm.core.bean.Upload;
import com.njit.mailm.core.bean.User;
import com.njit.mailm.core.dao.MailDao;
import com.njit.mailm.core.dao.UploadDao;
import com.njit.mailm.core.service.UploadService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by Administrator on 2016/5/8.
 */
@Transactional
@Service
public class UploadServiceImpl implements UploadService {

    @Autowired
    private UploadDao uploadDao;
    public boolean uploadAttchement(User user, MultipartFile file,String basePath,String draftId) {

        String userid = user.getId();

        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");

        String time = dformat.format(new Date());
        String filePath = null;
        // 判断文件是否为空
        if (!file.isEmpty()) try {
            String storgePath = basePath + "/" + userid + "/" + time + "/";
//
            // 文件保存路径

            filePath = storgePath + file.getOriginalFilename();

            IOUtil.createFile(new File(filePath));
            // 转存文件
            file.transferTo(new File(filePath));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        if(filePath != null){
            try {
                uploadDao.addAttachment(draftId,filePath);
            } catch (Exception e) {
                return false;
            }
            System.out.println("附件上传成功");
            return true;
        }else{
            return false;
        }

    }

    public List<Upload> findAttachment(String draftId) {

        return uploadDao.findUpload(draftId);
    }

}
